package com.core.basic.secure.suport;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.core.basic.secure.dao.ResourcesDao;
import com.core.basic.secure.dao.UsersDao;
import com.core.basic.secure.domain.Resources;
import com.core.basic.secure.domain.Users;

public class MyUserDetailsService implements UserDetailsService {
	private UsersDao usersDao;
	private ResourcesDao resourcesDao;
	
	public UsersDao getUsersDao() {
		return usersDao;
	}

	public void setUsersDao(UsersDao userDao) {
		this.usersDao = userDao;
	}
	public ResourcesDao getResourcesDao() {
		return resourcesDao;
	}

	public void setResourcesDao(ResourcesDao resourcesDao) {
		this.resourcesDao = resourcesDao;
	}

	public UserDetails loadUserByUsername(String account)
			throws UsernameNotFoundException {
		Users user = this.usersDao.findByProperty("account", account);
		if (user == null) {
			throw new UsernameNotFoundException(account);
		}
		Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(user);

		boolean enables = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;

		User userdetail = new User(user.getAccount(), user.getPassword(),
				enables, accountNonExpired, credentialsNonExpired,
				accountNonLocked, grantedAuths);
		return userdetail;
	}

	// 取得用户的权限
	private Set<GrantedAuthority> obtionGrantedAuthorities(Users user) {
		Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
		try{
			List<Resources> resources = null;
			if(user.getAccount().equals("admin")){
				resources=resourcesDao.findAll();
			}else{
				resources=resourcesDao.getUserResources(user.getId());
			}
			for (Resources res : resources) {
				System.out.println(res.getName());
				authSet.add(new GrantedAuthorityImpl(res.getName()));
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return authSet;
	}
}
